import React, {Component} from 'react';
import './SearchNav.css';

class SearchNav extends Component {
	constructor(props) {
		super(props);

		this.state = {
			keyword: '', // 关键词

		}
		this.shake = this.antiShake.call(this, 200);
	}

	componentDidMount() {
		// 把this发送给父组件使用
		this.props.getChild.call(this, this);

	}

	// 把父组件传的参数放到输入框
	changeChild(keyword) {
		// console.log(keyword);
		this.setState(state => {
			return {
				keyword,
			}
		})
	}

	// 输入框改变事件
	changeInp(e) {
		let value = e.target.value
		this.setState(state => {
			return {
				keyword: value
			}
		}, () => {
			this.shake();
		})

	}

	// 防抖
	antiShake(wait) {
		let timer = null;
		return function () {
			if (timer !== null) {
				clearInterval(timer);
			}
			timer = setTimeout(() => {
				// 触发父的输入框改变事件
				this.props.getListByKeyword(this.state.keyword);
			}, wait)
		}

	}

	// 返回按钮
	clickBack() {
		// 触发父的返回事件
		this.props.pageBack();
	}

	// 清空输入框
	clearInp() {
		this.setState(state => {
			return {
				keyword: ''
			}
		})

		// 触发父的输入框清空事件
		this.props.cleanKeyword();
	}

	render() {
		return (
			<div className='searchNav'>
				<div className="nav-fixed">
					<i className='back iconfont icon-arrowleftzuojiantou' onClick={this.clickBack.bind(this)}/>
					<input className='inp' placeholder='搜索歌曲、歌手、专辑' value={this.state.keyword}
						onChange={this.changeInp.bind(this)} type="text"/>
					{this.state.keyword.length ?
						<i className='clear iconfont icon-cuocha' onClick={this.clearInp.bind(this)}/> : null}
				</div>
			</div>
		);
	}
}

export default SearchNav;